%% @author wenqi_zheng
%% @doc @todo Add description to echo_client.


-module(echo_client).

%% ====================================================================
%% API functions
%% ====================================================================
-export([start/1, start/3, send/2, run/4, connect/4, loop/2]).
-define(TCP_OPTIONS, [binary,
					  {packet, 4},
					  {buffer, 1024},
					  {active, true}]).


start([Port, Host, N])->
	start(Port, Host, N).

start(Port, Host, N) ->
	spawn(?MODULE, run, [self(), Host, Port, N]),
	mainloop(1).


mainloop(Count) ->
	receive
		{connected, _Sock} ->
			io:format("connected: ~p~n", [Count]),
			mainloop(Count+1)
	end.

run(_Parent, _Host, _Port, 0) ->
	ok;

run(Parent, Host, Port, N)->
	spawn(?MODULE, connect, [Parent, Host, Port, N]),
	timer:sleep(5),
	run(Parent, Host, Port, N-1).

connect(Parent, Host, Port, N) ->
	case gen_tcp:connect(Host, Port, ?TCP_OPTIONS, 60000) of
		{ok, Sock} -> 
			Parent ! {connected, Sock},
			random:seed(erlang:timestamp()),
			loop(N, Sock);
		{error, Error} ->
			io:format("client ~p connect error: ~p~n", [N, Error])
	end.


loop(N, Sock) ->
	Timeout = 5000+random:uniform(5000),
	receive
		{tcp, Sock, Data} -> 
			io:format("client ~p received: ~p~n", [N,  binary_to_term(Data)]), 
			loop(N, Sock);
		{tcp_closed, Sock} -> 
			io:format("client ~p socket closed~n", [N]);
		{tcp_error, Sock, Reason} -> 
			io:format("client ~p socket error: ~p~n", [N, Reason]);
		Other -> 
			io:format("client ~p unexpected: ~p", [N, Other])
	after
		Timeout -> send(N, Sock), loop(N, Sock)
	end.

send(N, Sock) ->
	%Data = iolist_to_binary(lists:duplicate(128, "00000000")),
	io:format("Send~n"),
	gen_tcp:send(Sock, [term_to_binary("list_to_tuple([20, 30])")]).

a2i(A) -> list_to_integer(atom_to_list(A)).






%% ====================================================================
%% Internal functions
%% ====================================================================


